#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <openssl/md5.h>
#include <libmemcached/memcached.h>

char *download(unsigned long size, char *server, unsigned char *key){
	int i, n;
	size_t s;
	unsigned char *key1, *key2;
	char *sName, *data;
	memcached_st *memc;
	memcached_return_t rc;

	key1 = (char *) malloc(16);
	key2 = (char *) malloc(sizeof(char) * 250);

	sName = (char *) malloc(sizeof(char) *(strlen(server) + 10));

	n = sprintf(sName, "--SERVER=%s", server);
	memc = memcached(sName, strlen(sName));
  //memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 1);
	if(memc == NULL){
		memcached_free(memc);
		free(key);
		free(data);
		return NULL;
	}

	data = memcached_get(memc, (unsigned char *) key, strlen(key), &s, (uint32_t) 0, &rc);

  if(data == NULL) return NULL;

	key1 = MD5(data, size, NULL);
	for(i = 0; i < 16; i++){
		sprintf(key2 + 2*i, "%.2x", key1[i]);
	}

	if(strcmp(key2, key) == 0){
		memcached_free(memc);
		free(sName);
		return data;
	}else{
		return NULL;
	}
}
